#!/user/bin/env python
# -*- coding: utf-8 -*-
# @Software: PyCharm
# @Time : 2021/05/13 20:45
# @Author : ziqi.zhang
# @Version : 1.0.0
# @Description : 执行测试用例的文件

import os
import time
import logging
import unittest
import configparser
import multiprocessing
from Common.Mail import Email
from Common.Logging import Logging
from Common.Config import ReadConfig
from Common.HTMLTestRunner_cn import HTMLTestRunner

now_time = time.strftime('%Y_%m_%d_%H_%M_%S')  # 用当前时间命名Html报告
Logging()  # 实例日志类


def email():
    """创建和发送邮件"""
    conf = configparser.ConfigParser()  # 读取配置文件的实例
    conf.read(ReadConfig().load_config(), encoding='utf8')  # 获取配置文件

    # 读取配置文件，判断是否发送邮件 switch = on 发送邮件，off不发送邮件
    switch = conf.get('Email', 'email_switch')
    if switch == 'off':
        logging.info('读取本地环境配置文件loc.ini，不发送邮件')
    else:
        logging.info('读取测试环境配置文件test.ini，开始发送邮件')

        # 发送报告邮件配置
        email_host = conf.get('Email', 'email_host')  # smtp邮件服务器
        host_port = conf.get('Email', 'host_port')  # smtp 邮件服务器端口：SSL连接
        from_addr = conf.get('Email', 'from_addr')  # 发件地址，现在这个是个人邮箱，部署后需要换成公司对外邮箱
        password = conf.get('Email', 'password')  # 发件地址的授权码，而非登录密码，腾讯企业邮箱可以用登录密码

        # 获取最新生成的测试报告附件
        result_dir = '../Report/'  # 测试报告路径
        lists = os.listdir(result_dir)  # 将路径下的所有文件都放到一个数组中
        source_path = []  # 用来存放最新报告的数组
        for i in range(len(lists)):
            j = lists[i][0:19]
            if j == now_time:  # 通过对面文件名和now_time是否先等来获取最新的html报告并加入到数组中
                source_path.append(result_dir + lists[i])

        # 邮件内容配置
        to_addr_list_all = conf.get('Email', 'to_addr_list_all')  # 邮件接收人
        to_addr_list = to_addr_list_all.split(",")  # 将收件人转化为列表
        email_content_html = conf.get('Email', 'email_content_html')  # 邮件正文的标题
        email_content = conf.get('Email', 'email_content')  # 邮件正文内容
        email_subject = conf.get('Email', 'email_subject')  # 邮件主题
        email_from = conf.get('Email', 'email_from')  # 邮件发送者
        part_name = []  # 用来存放报告文件名
        for i in range(len(source_path)):  # 获取最新的HTML报告文件名并加入数组中
            name = os.path.basename(source_path[i])
            part_name.append(name)

        # 发送邮件
        em = Email()
        email_obj = em.get_email_obj(email_subject, email_from, to_addr_list)  # 构造邮件
        em.attach_content(email_obj, email_content_html + '\n')  # 加入邮件正文标题
        em.attach_content(email_obj, email_content)  # 加入邮正文件内容
        for i in range(len(part_name)):
            em.attach_part(email_obj, source_path[i], part_name[i])  # 添加附件
        em.send_email(email_obj, email_host, host_port, from_addr, password, to_addr_list)  # 发送邮件


def process1():
    """进程1，执行测试并输出HTML报告"""
    test_dir = ''  # 用例文件的路径
    test_name = 'Test_Demo.py'
    dir_name = test_name[0:-3]
    TestCase1 = unittest.defaultTestLoader.discover(test_dir, pattern=test_name)  # 可以用正则匹配出要执行的用例文件
    fp = open('../Report/' + now_time + '_' + dir_name + '.html', 'wb')  # 新建文件
    unittest.TextTestRunner()  # 初始化unittest
    runner = HTMLTestRunner(stream=fp, title='测试报告', description='测试报告详情')  # 初始化HTML测试报告
    runner.run(TestCase1)  # 执行测试用例
    fp.close()  # 关闭HTML报告文件


def process2():
    """进程2，执行测试并输出HTML报告"""
    test_dir = ''  # 用例文件的路径
    test_name = 'Test_BaiduSearch.py'
    dir_name = test_name[0:-3]
    TestCase2 = unittest.defaultTestLoader.discover(test_dir, pattern=test_name)  # 可以用正则匹配出要执行的用例文件
    fp = open('../Report/' + now_time + '_' + dir_name + '.html', 'wb')  # 新建文件
    unittest.TextTestRunner()  # 初始化unittest
    runner = HTMLTestRunner(stream=fp, title='测试报告', description='测试报告详情')  # 初始化HTML测试报告
    runner.run(TestCase2)  # 执行测试用例
    fp.close()  # 关闭HTML报告文件


def run():
    """多进程执行测试用例"""
    processing = []
    p1 = multiprocessing.Process(target=process1)
    processing.append(p1)
    p2 = multiprocessing.Process(target=process2)
    processing.append(p2)
    for p in processing:
        p.start()
    for p in processing:
        p.join()


if __name__ == "__main__":
    run()
    email()
